import React from 'react';
import { FlatList, View, Text, RefreshControl } from 'react-native';
import viewStyles from './viewStyles';
import ViewX from './View';
import { IconX } from './iconx';

export function SafeContainer({ style, ...other }) {
  return (
    <ViewX {...other} style={[viewStyles.container, style]} useSafeAreaView />
  );
}

export function LoadingContainer({
  onRefresh,
  loading,
  header,
  emptyDesc = '暂无数据',
  footer,
  ...restProps
}) {
  const fallback = () => {};

  return (
    <FlatList
      keyboardShouldPersistTaps={'always'}
      nestedScrollEnabled
      removeClippedSubviews
      keyExtractor={(item) => String(item.id || item.key)}
      ListHeaderComponent={header}
      ListEmptyComponent={
        <View style={[viewStyles.container, viewStyles.center]}>
          <IconX origin="ant" name="inbox" size={48} />
          <Text>{emptyDesc}</Text>
        </View>
      }
      ListFooterComponent={footer}
      refreshControl={
        <RefreshControl
          enabled={onRefresh ? true : false}
          refreshing={onRefresh && loading ? true : false}
          onRefresh={onRefresh || fallback}
        />
      }
      stickyHeaderIndices={header ? [0] : undefined}
      contentContainerStyle={{ flexGrow: 1 }}
      {...restProps}
    />
  );
}

export const Container = ({ style, float, ...other }) => {
  const containerStyle = {};
  if (float === 'right') {
    containerStyle.alignItems = 'flex-end';
  } else if (float === 'left') {
    containerStyle.alignItems = 'flex-start';
  }
  return (
    <ViewX {...other} style={[viewStyles.container, style, containerStyle]} />
  );
};
